package com.nsn.das.midas.service.assembler.impl;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;

import com.nsn.das.midas.model.component.Build;
import com.nsn.das.midas.model.component.NetworkElement;
import com.nsn.das.midas.model.component.RevisionHistory;
import com.nsn.das.midas.model.user.DASUser;
import com.nsn.das.midas.service.BaseManager;
import com.nsn.das.midas.service.assembler.CommonAssembler;

@Component("commonAssembler")
public class CommonAssemblerImpl implements CommonAssembler {
	
	@Resource(name="baseManager")
	protected BaseManager baseManager;
	
	@Override
	public String buildRevisionHistory(List<RevisionHistory> historys){
		StringBuffer result = new StringBuffer();
		for(RevisionHistory history : historys){
			result.append(history.toString() + "\n");
		}
		
		return result.toString();
	}
	
	@Override
	public JSONObject buildAuthorJson(DASUser author) throws JSONException{
		JSONObject object = new JSONObject();
		object.put("id", author.getId());
		object.put("nsnId", author.getNsnId());
		object.put("name", author.getUsername());
		object.put("email", author.getEmail());
		return object;
	}

	@Override
	public JSONArray buildNetworkElementJson(Set<NetworkElement> elements) throws JSONException{
		JSONArray array = new JSONArray();
		for(NetworkElement element : elements){
			JSONObject o = new JSONObject();
			o.put("id", element.getId());
			o.put("value", element.getName());
			array.put(o);
		}
		return array;
	}

	@Override
	public JSONArray buildBuildsJson(Set<Build> builds) throws JSONException{
		JSONArray array = new JSONArray();
		for(Build build : builds){
			JSONObject o = new JSONObject();
			o.put("id", build.getId());
			o.put("release", build.getRelease().getName());
			o.put("build", build.getName());
			array.put(o);
		}
		return array;
	}

	@Override
	public DASUser getUserFromJson(JSONObject author) throws Exception{
		DASUser user;
		long id = Long.parseLong(author.getString("id"));
		if(id > 0){
			user = baseManager.getEntity(DASUser.class, id);
		}else{
			user = null;
		}
		user.setUsername(author.getString("name"));
		user.setEmail(author.getString("email"));
		return user;
	}

	@Override
	public RevisionHistory buildRevisionHistory(DASUser editor,String comment){
		RevisionHistory history = new RevisionHistory();
		history.setAuthor(editor);
		history.setComment(comment);
		history.setCreatedAt(new Date(System.currentTimeMillis()));
		return history;
	}
}
